<?php
//快递查询
function kuaidi($com = '', $num = '')
{


    $key = 'jcOqojpa620';                        //客户授权key
    $customer = '29A40FC666F0B24441D3D8EFDC919731';//查询公司编号
    $param = array(
        'com' => $com,             //快递公司编码
        'num' => $num,     //快递单号
        'phone' => '',                //手机号
        'from' => '',                 //出发地城市
        'to' => '',                   //目的地城市
        'resultv2' => '1'             //开启行政区域解析
    );

    //请求参数
    $post_data = array();
    $post_data["customer"] = $customer;
    $post_data["param"] = json_encode($param);
    $sign = md5($post_data["param"] . $key . $post_data["customer"]);
    $post_data["sign"] = strtoupper($sign);

    $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址

    $params = "";
    foreach ($post_data as $k => $v) {
        $params .= "$k=" . urlencode($v) . "&";              //默认UTF-8编码格式
    }
    $post_data = substr($params, 0, -1);
// echo '请求参数<br/>'.$post_data;
    //发送post请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    $data = str_replace("\"", '"', $result);
    $data = json_decode($data);
    return $data;
    // echo '<br/><br/>返回数据<br/>';
    // dump($data);

}

//快递可用查询
function kuaidi_usable($com = '', $num = '')
{
    $key = 'jcOqojpa620';                        //客户授权key
    $customer = '29A40FC666F0B24441D3D8EFDC919731';//查询公司编号
    $secret = 'f84a5c6edc054a8c9f9483b58a38d05c';//查询公司编号
    $param = array(
        'recManName' => "刘Liu",             //收件人姓名
        'recManMobile' => "17535210323",             //收件人的手机号
        'recManPrintAddr' => "上海市徐汇区华山路1954号",             //收件人所在完整地址，如广东深圳市深圳市南山区科技南十二路2号金蝶软件园
        'sendManName' => "六六六",             //寄件人姓名
        'sendManMobile' => "17535210323",             //寄件人的手机号
        'sendManPrintAddr' => "美国",             //寄件人所在完整地址，如广东深圳市深圳市南山区科技南十二路2号金蝶软件园
        'kuaidiComs' => "yuantong"         //快递公司编码
    );

    //请求参数
    $body = [];
    $body["method"] = "reachable";
    $body["key"] = $key;
    $body["param"] = json_encode($param);
    $body["t"] = time();
    $sign = strtoupper(md5($body["param"].$body["t"] . $key . $secret));
    $body["sign"] = strtoupper($sign);
    $params = "";
    foreach ($body as $k => $v) {
        $params .= "$k=" . urlencode($v) . "&";              //默认UTF-8编码格式
    }
    $body = substr($params, 0, -1);

    $url = 'http://api.kuaidi100.com/reachable.do';    //实时查询请求地址
    //发送post请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type' => "application/x-www-form-urlencoded"]);
    $result = curl_exec($ch);
    $data = str_replace("\"", '"', $result);
    $data = json_decode($data);
    return $data;
    // echo '<br/><br/>返回数据<br/>';
    // dump($data);
}

/**
 *
 * 把对象转成数组
 * @param $object 要转的对象$object
 */
function objectToArray($object)
{

    $result = array();

    $object = is_object($object) ? get_object_vars($object) : $object;

    foreach ($object as $key => $val) {

        $val = (is_object($val) || is_array($val)) ? objectToArray($val) : $val;

        $result[$key] = $val;
    }

    return $result;
}

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, true);
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }


    /**
     * 全部推送
     * content内容
     */
    function jpush_stu_all($content, $pushmessage_id = 0)
    {
        vendor('Jpush.autoload');
        $app_key = '08829e43ae55e84910a1b2b4';
        $master_secret = '67ca357f7e42b85eeba1a016';

        $client = new JPush\Client($app_key, $master_secret);

        $push_payload = $client->push()
            ->setPlatform('all')
            ->addAllAudience()
            ->setNotificationAlert($content)
            /*->message('hello message', array(
            'title' => 'hello title',
            'extras' => array(
                'status' => '1'
            )))*/
            ->androidNotification($content, array(
                'extras' => array(
                    'status' => 1,
                    'pushmessage_id' => $pushmessage_id
                )))
            ->iosNotification($content, array(
                'extras' => array(
                    'status' => 1,
                    'pushmessage_id' => $pushmessage_id
                ),
            ));
        try {
            $response = $push_payload->send();
            // print_r($response);
        } catch (\JPush\Exceptions\APIConnectionException $e) {
            // try something here
            //print $e;
        }

    }


    /**
     * 单个推送
     * content内容
     * regis设备is 数组
     * status 类型
     * type   1 系统消息，2 订单消息
     * user_type    1 买家，2 卖家
     */
    function jpush_stu_single($user_id, $content, $id, $type = 1)
    {
        vendor('Jpush.autoload');
        $app_key = '08829e43ae55e84910a1b2b4';
        $master_secret = '67ca357f7e42b85eeba1a016';

        $client = new JPush\Client($app_key, $master_secret);
        // dump($client);die;
        $pusher = $client->push();
        $pusher->setPlatform('all');

        $pusher->addAlias($user_id);
        // $pusher->addTagAnd($phone);

        $pusher->setNotificationAlert($content);
//        $pusher->options(array(
//             'apns_production' => true
//        ));                        //判断ios是否线上调用,线上调用不用设置该项,直接注释,线下调用true
        $pusher->options(array(
            'apns_production' => true
        ));
        $pusher->iosNotification($content, array(
            'title' => '',
            'extras' => array(
                'sound' => 'default',
                'type' => $type,
                // 'avatar'=>$avatar,
                'id' => $id
            ),
        ));
        $pusher->androidNotification($content, array(
            'title' => '',
            'extras' => array(
                'type' => $type,
                'id' => $id
            ),
        ));

        try {
            $pusher->send();
        } catch (\JPush\Exceptions\JPushException $e) {
            return;
        }
    }


}
